
import { _decorator, Color, easing, EventTouch, instantiate, Label, Node, Prefab, sp, Sprite, SpriteFrame, Tween, tween, UIOpacity, UITransform, v3, Vec3 } from 'cc';
import { BaseUI } from '../../framework/base/BaseUI';
import { ADType, BaseEventName } from '../../framework/config/Appcfg';
import { AudioMgr } from '../../framework/manager/AudioMgr';
import { SDKMgr } from '../../framework/manager/SDKMgr';
import { UIMgr } from '../../framework/manager/UIMgr';
import { AnimtorUtils } from '../../framework/utils/AnimtorUtils';
import { Utils } from '../../framework/utils/Utils';
import { AudioId, EventName, UIID } from '../config/Config';
import { BgBlock } from '../gameLogic/BgBlock';
import { GameDef } from '../gameLogic/GameDef';
import { GameLogicMgr, levelData } from '../gameLogic/GameLogicMgr';
import { PlayerMgr } from '../manager/PlayerMgr';
import { ColorBlock } from '../uiItem/ColorBlock';
import { GuildCfg } from './UIGuide';
const { ccclass, property } = _decorator;

@ccclass('UIGame')
export class UIGame extends BaseUI {
    @property(Prefab)
    public colorBlockPrefab: Prefab = null;
    @property(Prefab)
    public bgBlockPrefab: Prefab = null;

    @property(SpriteFrame)
    public comboSprites: SpriteFrame[] = [];

    private nodeArr: Node[][] = [];

    /**背景色块对象数组 */
    private bgNodeBlocks: Node[][] = [];
    /**色块大小 */
    colorBlockSize: number = 0;
    /**点击用时 */
    clickTimer: number = 0;
    /**消除用时 */
    clearTimer: number = 0;
    /**当前段位 */
    gameType: number = 0;
    /**是否有加成卡 */
    isUseBoundCard: boolean = false;
    /**又3个时，需要单次点击选中两个 */
    isClickToDo: boolean = false;
    /**记录点击的色块坐标 */
    saveClickColorBlock: number[][] = [];
    /**记录点击的色块坐标 */
    saveClickColorBlockNode: Node[] = [];
    /**当前单击色块的坐标 */
    curClickColorBlock: number[][] = [];

    aniNodePool: Node[] = [];
    clearSpineNodePool: Node[] = [];
    paddingBottom: number = 30;

    currSkinInde = 0;

    gameProgress: number = 0;
    allColorBlockNum: number = 0;
    clearColorBlockNum: number = 0;
    // 在类顶部添加临时变量
    private _tempScore: number = 0;
    private _tempPoints: number = 0;
    private startScore: number = 0;
    private startPoints: number = 0;
    tipTimes: number = 0;

    private tipNodes: Node[] = [];

    public init(param1?: any, param2?: any, param3?: any, param4?: any, param5?: any): void {
        this.param = param1;
        this.gameType = param1;
        GameDef.instance.reportInfo.gameType = this.gameType;
    }
    protected onLoad(): void {

        AudioMgr.getInstance().playMusic(AudioId.gameBgm, "MainBGM");
    }
    public start(): void {
        this.addEvent(EventName.CLICK_COLOR_BLOCK, this.onClickColorBlock)
        this.findChilds("tishi").on("click", this.onClickHint, this)
        this.findChilds("qiaosui").on("click", this.onClickCrack, this)
        this.findChilds("qinchu").on("click", this.onClickRefresh, this)
        this.findChilds("guize").on("click", this.onOpenRolue, this)
        this.findChilds("btnZhanTing").on("click", this.onClickZhanTing, this)
        this.addEvent(BaseEventName.Video_Revival, this.onVideoRevival)
        this.addEvent(BaseEventName.ReplayGame, this.onReplayGame)
        this.addEvent(BaseEventName.playNextLevel, this.onPlayNextLevel)
        this.tipNodes = [this.findChilds("qipaotishi1"), this.findChilds("qipaotishi2"), this.findChilds("qipaotishi3")]
        this.onReplayGame()
        this.refreshSkillBtnUI()
        if (PlayerMgr.instance.userData.data.showTipLevelOnes[this.gameType] === -1 && this.gameType != 3) {
            UIMgr.instance.openUI(UIID.UIRolue, UIID.Default, true, this.gameType)
            PlayerMgr.instance.userData.data.showTipLevelOnes[this.gameType] = 0;
            PlayerMgr.instance.userData.saveDataToLocad()
        }
        this.showGuide()
        if (!PlayerMgr.instance.isNewGuide) {
            this.schedule(this.onUpdata, 1)
            this.schedule(this.startShowSkillTip,1)
        }
    }
    refreshSkillBtnUI(): void {
        let skillBtns = this.findChilds("skillBtns").children
        for (let i = 0; i < skillBtns.length; i++) {
            let shipingNode = skillBtns[i].getChildByName("shipin");
            let countNode = skillBtns[i].getChildByName("count");
            let skillCount = PlayerMgr.instance.getSkillCount(i + 1);
            if (skillCount > 0) {
                shipingNode.active = false;
                countNode.active = true;
                countNode.getComponent(Label).string = "x" + skillCount;
            } else {
                shipingNode.active = true;
                countNode.active = false;
            }
        }
    }
    onPlayNextLevel(gameType: number): void {
        this.gameType = gameType;
        this.onReplayGame()
    }
    /**
     * 重新开始游戏
     */
    onReplayGame() {
        const levelData = this.initData();
        GameDef.instance.reInit()
        this.initAniNodePool()
        this.updataScoreText()
        this.createBgColorBlock(levelData);
        this.createLevelData(levelData)
        this.findChilds("chipang").getComponent(sp.Skeleton).setSkin("ka" + (this.currSkinInde + 1))
    }
    /**
     * 初始化数据
     */
    initData() {
        const levelData = GameDef.instance.getLevelData(this.gameType);
        this.startScore = 0;
        this.startPoints = 0;
        this._tempScore = 0;
        this._tempPoints = 0;
        this.clearTimer = 0
        this.clickTimer = 0
        this.currSkinInde = 0;
        this.isUseBoundCard = false
        this.tipTimes = 0;
        GameDef.instance.MapSize[0] = levelData.wh;
        GameDef.instance.MapSize[1] = levelData.wh;
        GameDef.instance.MapSize[2] = levelData.wh;
        return levelData;
    }
    initAniNodePool() {
        let nodes = this.findChilds("effectLayer").children;
        for (let i = 0; i < nodes.length; i++) {
            this.aniNodePool.push(nodes[i])
        }
        this.clearSpineNodePool.push(this.findChilds("xiaochu0"), this.findChilds("xiaochu1"), this.findChilds("xiaochu2"), this.findChilds("xiaochu3"))
        this.findChilds("xiaochu0").removeFromParent()
        this.findChilds("xiaochu1").removeFromParent()
        this.findChilds("xiaochu2").removeFromParent()
        this.findChilds("xiaochu3").removeFromParent()
        this.findChilds("effectLayer").removeAllChildren()
    }
    //创建颜色背景快矩阵
    public createBgColorBlock(levelData: { levelData: { value: number, count: number }[], obstacles: { 1: number[], 2: number[] }, wh: number[] }) {
        this.findChilds("grid").destroyAllChildren()
        let size = GameDef.instance.BlockSize[this.gameType]
        this.colorBlockSize = size;
        let wh = levelData.wh;
        let layerSize = this.findChilds("grid").getComponent(UITransform);
        layerSize.height = wh[1] * size;
        layerSize.width = wh[0] * size;
        this.findChilds("center").getComponent(UITransform).height = wh[1] * size + this.paddingBottom;
        for (let j = 0; j < wh[1]; j++) {
            this.bgNodeBlocks[j] = [];
            for (let i = 0; i < wh[0]; i++) {
                let node = instantiate(this.bgBlockPrefab);
                node.getComponent(BgBlock).init(i, j).setSize(size, size)//.setColor((i + j) % 2 == 0 ? "#d8e4f6" : "#c9cdee");
                node.setPosition(i * (size) + size / 2 - layerSize.width / 2, -(j * (size) + size / 2) + layerSize.height / 2);
                this.findChilds("grid").addChild(node);
                this.bgNodeBlocks[j][i] = node;
            }
        }
    }
    /**根据数据生成关卡 */
    public createLevelData(levelData: { levelData: { value: number, count: number }[], obstacles: { 1: number[], 2: number[] }, wh: number[] }) {
        const whiteBlock = this.findChilds("gameLayer").getChildByName("whiteBlock")
        whiteBlock.removeFromParent()
        this.findChilds("gameLayer").destroyAllChildren();
        this.findChilds("gameLayer").addChild(whiteBlock)
        let wh = levelData.wh;
        GameLogicMgr.instance.init();
        console.log("levelData", levelData);
        if (PlayerMgr.instance.isNewGuide) {
            GameLogicMgr.instance.playNewGuideData(GameDef.instance.newGuideLevelData)
        } else {
            GameLogicMgr.instance.generateColorGrid2(wh[1], wh[0], levelData.levelData)
            this.selectMaskColorBlock(levelData.obstacles);
        }
        this.createClearColorBlock(GameLogicMgr.instance.levelData, this.colorBlockSize);
    }
    selectMaskColorBlock(maskTypeData: { 1: number[], 2: number[] }) {
        // 获取难度等级
        // 遍历遮罩类型配置
        for (const maskTypeStr in maskTypeData) {
            // 获取当前关卡所有色块信息
            const { colorCountObj, len } = GameLogicMgr.instance.checkAllColorCount();
            //  获取当前遮罩类型的配置信息
            const maskType = Number(maskTypeStr);
            const colorData = maskTypeData[maskTypeStr];
            const baseMaskCount = colorData[0];

            // 计算每个颜色应分配的遮罩数量
            const colorKeys = Object.keys(colorCountObj);
            const totalBlocks = colorKeys.reduce((sum, key) => sum + colorCountObj[key].length, 0);
            let maskCountData = Utils.dynamicDistribution1(baseMaskCount, colorKeys.length)
            console.log("datas1", maskCountData, baseMaskCount, colorKeys.length)
            let index = 0;
            // 为每种颜色分配遮罩
            for (const colorKey in colorCountObj) {
                const colorBlocks = colorCountObj[colorKey];
                const ratio = colorBlocks.length / len;
                const count = maskCountData[index] * 2
                // 随机选择色块并设置遮罩
                const maskedBlocks = GameLogicMgr.instance.getRandomValues(colorBlocks, count);
                maskedBlocks.forEach(block => {
                    block.maskType = maskType;
                    block.maskCount = 1;
                });
                index++
                // console.debug("遮罩分配统计", {
                //     比例: ratio,
                //     遮罩数: baseMaskCount,
                //     类型: maskType,
                //     数量: count,
                //     总色块数: colorBlocks.length,
                //     总长度: len,
                // });
            }
        }

        console.groupEnd()
        // console.log("colorCountObj", )
    }

    showRuleView() {
        console.log("显示规则界面")
    }

    /**进入游戏时 创建消除色块矩阵 */
    private createClearColorBlock(arr: levelData[][], size: number) {
        console.log("arrData", arr);
        let index = 0;
        this.nodeArr = [];
        let layerSize = this.findChilds("gameLayer").getComponent(UITransform);
        layerSize.height = GameDef.instance.MapSize[this.gameType][1] * size;
        layerSize.width = GameDef.instance.MapSize[this.gameType][0] * size;
        for (let j = 0; j < arr.length; j++) {
            this.nodeArr[j] = [];
            for (let i = 0; i < arr[j].length; i++) {
                if (arr[j][i].value > 0) {
                    this.addColorNodeToLayer(i, j);
                    index++;
                }
            }
        }
        this.allColorBlockNum = index;
        this.clearColorBlockNum = 0;
    }
    /**
     * 
     * @param event
     */
    private addColorNodeToLayer(i: number, j: number, Node?: Node) {
        let arr = GameLogicMgr.instance.levelData;
        let node = Node || instantiate(this.colorBlockPrefab);
        let test = false
        let size = this.colorBlockSize;
        let layerSize = this.findChilds("gameLayer").getComponent(UITransform);
        node.scale = v3(0, 0, 0)
        node.getComponent(ColorBlock).x = i;
        node.getComponent(ColorBlock).y = j;
        node.getComponent(ColorBlock).type = arr[j][i].value;
        if (test) {
            node.getComponent(Sprite).color = new Color().fromHEX(GameDef.instance.BlockColor[arr[j][i].value - 1])
            tween(node).delay(0.04 * (j + i))
                .to(0.15, { scale: v3(1.4, 1.4, 1.4) })
                .to(0.15, { scale: v3(0.8, 0.8, 0.8) })
                .to(0.07, { scale: v3(1.08, 1.08, 1.08) })
                .start()
        } else {
            node.getComponent(Sprite).spriteFrame = null;
            node.name = "guodong" + arr[j][i].value;
            node?.skin("guodong" + arr[j][i].value, GameDef.instance.gameSkin, (spriteFrame) => {
                tween(node).delay(0.04 * (j + i))
                    .to(0.15, { scale: v3(1.4, 1.4, 1.4) })
                    .to(0.15, { scale: v3(0.8, 0.8, 0.8) })
                    .to(0.07, { scale: v3(1.08, 1.08, 1.08) })
                    .start()
            })
            this.setMaskColorSkin(node, arr[j][i].maskType)
        }
        node.getComponent(UITransform).setContentSize(size, size);
        node.setPosition((i * size + size / 2) - layerSize.width / 2, -(j * size + size / 2) + layerSize.height / 2);
        this.nodeArr[j][i] = node;
        !node.disEnable && this.nodeArr[j][i].onClick(this.onClickSelectBlock, this);
        node.setParent(this.findChilds("gameLayer"));
    }

    /**
     * 点击色块，判断是否达到消除逻辑
     * @param row 行
     * @param col 列
     */
    row: number = 0;
    col: number = 0;
    isCanClickClock: boolean = true;
    onClickColorBlock(row: number, col: number) {
        this.skillTipTimer = 0
        if (!this.isCanClickClock) return;
        this.isCanClickClock = false;
        if (GameLogicMgr.instance.levelData[row][col].value > 0) {
            this.node.startShake(0.2, 8)
            this.isCanClickClock = true;
            return;
        }
        console.log("row:" + row, "-", "col:" + col, "   value:" + GameLogicMgr.instance.levelData[row][col].value);
        this.row = row;
        this.col = col;
        var isMaskType2Arr: number[][] = []
        const objArr = GameLogicMgr.instance.findNonZeroBlocksInCross(row, col);
        const obj = GameLogicMgr.instance.groupBlocksByValue(objArr);
        let isClear = false;
        this.isClickToDo = false;
        // return
        for (const key in obj) {
            for (let i = obj[key].length - 1; i >= 0; i--) {
                if (obj[key][i][3] === 2) {
                    isMaskType2Arr.push(obj[key].splice(i, 1)[0]);
                }
            }
            if (obj[key].length === 0) {
                delete obj[key];
            }
        }
        obj['mask'] = isMaskType2Arr
        // return;
        //先找到遮罩类型是2，并且数量为3个的对象
        if (isMaskType2Arr.length >= 3) {
            this.showSelectAniLayer(isMaskType2Arr)
        }
        for (const key in obj) {
            if (obj[key].length === 3) {
                this.showSelectAniLayer(obj[key])
                break;
            }
        }

        if (this.isClickToDo) {
            console.log("需要单次点击")
            this.isCanClickClock = true;
            return;
        } else {
            let index = 0
            for (const key in obj) {
                if (obj[key].length >= 2) {
                    for (const item of obj[key]) {
                        let data = GameLogicMgr.instance.checkCutMaskColorCount(item[0], item[1], -1)
                        if (index < 4) {
                            // this.findChilds("xiaochu" + index).active = true;
                            // this.findChilds("xiaochu" + index).setWorldPosition(this.nodeArr[item[0]][item[1]].getWorldPosition())
                            // this.findChilds("xiaochu" + index).getComponent(sp.Skeleton).setAnimation(0, "animation1", false)
                            index++
                        }
                        if (data.maskCount === 0) {
                            GameLogicMgr.instance.changeLevelData(item[0], item[1], 0)
                            this.playClearAni(this.nodeArr[item[0]][item[1]], [item[0], item[1]])
                            this.nodeArr[item[0]][item[1]] = null;
                            isClear = true;
                        } else {
                            if (data.maskType === 1) {
                                this.nodeArr[item[0]][item[1]].getChildByName("maskColor").active = false;
                            } else if (data.maskType === 2) {
                                this.nodeArr[item[0]][item[1]].getChildByName("maskColorAll").active = false;
                            }
                        }
                        this.clearColorBlockNum++;
                        this.scheduleOnce(() => {
                            this.isCanClickClock = true;
                        }, 0.3)
                        this.scheduleOnce(() => {
                            this.playClearSound()
                        }, 0.4)
                    }
                }
            }

        }
        if (isClear) {
            this.onCanClearBlock()
        } else {
            this.isCanClickClock = true;
            // this.node.startShake(0.2, 8)
            console.log("不满足消除条件")
        }
    }
    private showSelectAniLayer(arr: number[][]) {
        for (const item of arr) {
            this.nodeArr[item[0]][item[1]].zIndex = 888
            AnimtorUtils.moveAndScale(this.nodeArr[item[0]][item[1]], 0, 1, true, 0.5).start()
        }
        this.curClickColorBlock = arr
        if (this.findChilds("whiteBlock")) {
            this.findChilds("whiteBlock").active = true
            tween(this.findChilds("whiteBlock").getComponent(UIOpacity)).to(0.1, { opacity: 186 }).start()
            this.findChilds("whiteBlock").zIndex = 887;
        }
        console.log("有3个", arr)
        this.isClickToDo = true;
    }
    /**
     * 单选
     * @param row y
     * @param col x
     * @returns 
     */
    private lastSelectNode: Node = null
    private onClickSelectBlock(event: EventTouch) {
        this.skillTipTimer = 0
        const row = event.target.getComponent(ColorBlock).y;
        const col = event.target.getComponent(ColorBlock).x;
        if (GameLogicMgr.instance.skillUseStatus) {
            if (GameLogicMgr.instance.levelData[row][col].maskType === 2) {
                UIMgr.getInstance().showTip("不可敲碎木块")
            }
            else if (GameLogicMgr.instance.levelData[row][col].value > 0) {
                GameLogicMgr.instance.skillUseStatus = false
                GameLogicMgr.instance.changeLevelData(row, col, 0)
                this.nodeArr[row][col].destroy()
                this.nodeArr[row][col] = null;
                this.clearColorBlockNum++;
                AudioMgr.getInstance().playEffect(AudioId.knock)
                this.checkGameResult()
            } else {
                UIMgr.getInstance().showTip("请先击碎一个色块")
            }
            return;
        }
        if (!this.isClickToDo) return
        //取消选中效果
        let isUnSelect = false;
        for (let i = this.saveClickColorBlock.length - 1; i >= 0; i--) {
            if (this.saveClickColorBlock[i][0] == row && this.saveClickColorBlock[i][1] == col) {
                AnimtorUtils.moveAndScale(this.nodeArr[row][col], 0, 1, true, 0.5).start()
                this.saveClickColorBlock.splice(i, 1)
                this.curClickColorBlock.push([row, col])
                this.nodeArr[row][col].skin(this.nodeArr[row][col].name, GameDef.instance.gameSkin)
                isUnSelect = true;
                break;
            }
        }
        if (isUnSelect) return;
        //显示选中效果
        for (let i = this.curClickColorBlock.length - 1; i >= 0; i--) {
            if (this.curClickColorBlock[i][0] == row && this.curClickColorBlock[i][1] == col) {
                AnimtorUtils.stopMoveAndScale(this.nodeArr[row][col])
                this.saveClickColorBlock.push([row, col])
                this.curClickColorBlock.splice(i, 1)
                this.nodeArr[row][col].skin(this.nodeArr[row][col].name + "_a", GameDef.instance.gameSkin)
                break;
            }
        }
        if (this.saveClickColorBlock.length === 2) {
            let index = 0
            for (let item of this.saveClickColorBlock) {
                let data = GameLogicMgr.instance.checkCutMaskColorCount(item[0], item[1], -1)
                if (index < 2) {
                    // this.findChilds("xiaochu" + index).active = true;
                    // this.findChilds("xiaochu" + index).setWorldPosition(this.nodeArr[item[0]][item[1]].getWorldPosition())
                    // this.findChilds("xiaochu" + index).getComponent(sp.Skeleton).setAnimation(0, "animation1", false)
                    index++
                }
                if (data.maskCount === 0) {
                    GameLogicMgr.instance.changeLevelData(item[0], item[1], 0)
                    this.playClearAni(this.nodeArr[item[0]][item[1]], [item[0], item[1]])
                    this.nodeArr[item[0]][item[1]] = null;
                } else {
                    let node = this.nodeArr[item[0]][item[1]]
                    if (data.maskType === 1) {
                        node.getChildByName("maskColor").active = false;
                    } else if (data.maskType === 2) {
                        node.getChildByName("maskColorAll").active = false;
                    }
                    this.scheduleOnce(() => {
                        node?.skin(node.name, GameDef.instance.gameSkin)
                    }, 0.3)
                    this.scheduleOnce(() => {
                        node?.skin(node.name, GameDef.instance.gameSkin)
                    }, 0.6)
                    node?.skin(node.name, GameDef.instance.gameSkin)
                    node.zIndex = 0;
                    console.warn("消除后的数据", item[0], item[1], node)
                }

                this.clearColorBlockNum++;
            }
            tween(this.findChilds("whiteBlock").getComponent(UIOpacity)).to(0.1, { opacity: 0 }).call(() => {
                this.findChilds("whiteBlock").active = false
            }).start()
            for (let i = this.curClickColorBlock.length - 1; i >= 0; i--) {
                let node = this.nodeArr[this.curClickColorBlock[i][0]][this.curClickColorBlock[i][1]]
                if (node) {
                    node?.skin(node.name, GameDef.instance.gameSkin)
                    node.zIndex = 0;
                    AnimtorUtils.stopMoveAndScale(node)
                }
            }

            this.playClearSound()
            console.log("currLevelData", GameLogicMgr.instance.levelData, this.curClickColorBlock);
            this.isClickToDo = false;
            this.saveClickColorBlock = []
            this.curClickColorBlock = []
            this.onCanClearBlock()
        }
        console.log("row:" + row, "-", "col:" + col, this.curClickColorBlock);
    }
    private claerColorBlock(index: number) {


    }
    private onClickZhanTing() {
        UIMgr.instance.openUI(UIID.UISetting, UIID.Default, false, "暂停")
    }
    private onVideoRevival() {
        this.onClickRefreshVideo()
    }
    /**可以消除执行一下逻辑 */
    private onCanClearBlock() {
        if (this.clickTimer > GameDef.instance.comboTime) {
            this.clickTimer = 0
            GameDef.instance.comboCount = 0;
        } else {
            GameDef.instance.comboCount++;
            this.clickTimer = 0;
        }
        this.scoreCalculation()
        this.playComboSound()
        this.playComboAni()
        // console.log("消除后的数据", Utils.clonObj(GameLogicMgr.instance.levelData))
        GameDef.instance.reportInfo.levelPorgress = Math.floor((this.clearColorBlockNum / this.allColorBlockNum) * 100)
        console.log("当前进度：", GameDef.instance.reportInfo.levelPorgress + "%")
        this.clearTimer = 0
        this.tipTimes = 0;
        /****************************其他操作********************************* */
        this.checkGameResult()
        AudioMgr.getInstance().playEffect(AudioId.btnClick)
        this.hideSkillTip()
    }
    /**检测色块情况，判断输赢 */
    private checkGameResult() {
        let autoFindReult = GameLogicMgr.instance.findZeroBlocks()
        if (autoFindReult.length > 0) {
            // console.log("可以消除的色块", autoFindReult)
            this.hiedTipAniNode()
        } else {
            if (GameLogicMgr.instance.checkLevelDataAllIsZero()) {
                if (this.gameType === 0) {
                    PlayerMgr.instance.setUnlockLevel(1)
                } else if (this.gameType === 1) {
                    PlayerMgr.instance.setUnlockLevel(2)
                }

                setTimeout(() => {
                    UIMgr.getInstance().openUI(UIID.UIOver, UIID.Default, 'win', true, this.gameType)

                    console.log("游戏结束，所有色块都被消除了，你赢了")
                }, 1000);
            } else {
                // 执行补齐操作
                if (GameLogicMgr.instance.checkLevelDataHasSingleColorBlocks()) {
                    console.warn("无有可以消除的色块，需要补齐总数为单数色块")
                    this.completeColorBlock()
                    this.hiedTipAniNode()
                    if (GameLogicMgr.instance.findZeroBlocks().length <= 0) {
                        UIMgr.getInstance().openUI(UIID.UIResurrect, UIID.Default, 'lose', false, this.gameType)
                    } else {
                        console.log("有消除的色块")
                    }
                } else {
                    //游戏结束，输了
                    UIMgr.getInstance().openUI(UIID.UIResurrect, UIID.Default, 'lose', false, this.gameType)
                }
            }
        }
    }
    private playClearSound() {
        AudioMgr.getInstance().playEffect(AudioId.clear)
    }
    /**播放消除动画 */
    private playClearAni(node: Node, pos: number[] = []) {
        console.warn("执行消除动画")
        let x = this.colorBlockSize * this.col + this.colorBlockSize / 2 - this.findChilds("grid").getComponent(UITransform).width / 2;
        let y = -(this.colorBlockSize * this.row + this.colorBlockSize / 2) + this.findChilds("grid").getComponent(UITransform).height / 2 - this.paddingBottom / 2;
        this.showAndHidePath([pos[0], pos[1]], [this.row, this.col], 'show')
        let aniNode = this.aniNodePool.pop()
        node?.skin(node.name, GameDef.instance.gameSkin)
        node.offAllClick();
        node.disEnable = true;
        node.zIndex = 999;
        // Tween.stopAllByTarget(node)
        if (aniNode) {
            this.findChilds("effectLayer").addChild(aniNode)
            aniNode.active = true;
            aniNode.position = node.position.clone()
            Tween.stopAllByTarget(aniNode)
            tween(aniNode).to(0.3, { position: v3(x, y, 0) }, { easing: 'backIn' }).delay(0.8)
                .call((node: Node) => {
                    node.removeFromParent()
                    this.aniNodePool.push(node)
                    console.log("动画完成，回收到对象池", this.aniNodePool)
                }).start()
        }
        tween(node)
            .to(.3, { position: v3(x, y, 0) }, { easing: 'backIn' })
            .to(.1, { scale: v3(0, 0, 0) })
            .call(() => {
                console.log("caonim")
            })
            .to(.2, { scale: v3(1.5, 1.8, 0) })
            .to(.1, { scale: v3(1.8, 1.5, 0) })
            .to(.1, { scale: v3(1, 1, 0) })
            .to(.1, { scale: v3(1.8, 1.8, 0) })
            .to(.1, { scale: v3(1, 1, 0) })
            .call((node: Node) => {
                AnimtorUtils.parabolicMotion({
                    start: node.getWorldPosition().clone(),
                    end: this.findChilds("pointEat").getWorldPosition().clone(),
                    duration: 500,
                    args: node,
                    runCallback: (pos: Vec3) => {
                        node?.setWorldPosition(pos)
                    },
                    endCallback: (nodes) => {
                        tween(nodes)
                            .to(0.3, { scale: v3(0, 0, 0) })
                            .call(() => {
                                this.findChilds("chipang").getComponent(sp.Skeleton).setAnimation(0, "daiji", true)
                            }).start()
                        console.log("结束了", nodes)
                    }
                })
                // this.onPlayEatAni()
            })
            .start()

        // tween(node)
        //     .delay(1.1)
        //     .to(0.3, { scale: v3(1.6, 1.6, 0) })
        //     .to(0.1, { scale: v3(0.8, 0.8, 0) })
        //     .start()
        tween(node.getComponent(UIOpacity))
            .by(1.2, { opacity: 255 })
            .call((node: UIOpacity) => {

                this.findChilds("chipang").getComponent(sp.Skeleton).setAnimation(0, "chi", false)
                setTimeout(() => {
                    AudioMgr.getInstance().playEffect(AudioId.eat)
                }, 200);
                // node.destroy()
                // node.node.destroy()
            }).delay(0.4)
            .to(0.3, { opacity: 0 })
            .start()
        Tween.stopAllByTarget(this.node)
        tween(this.node).delay(0.6).call(() => {
            console.log("横说竖说")
            let spine = this.clearSpineNodePool.pop()
            this.findChilds("aniLayer").addChild(spine)
            spine.setPosition(v3(x, y, 0))
            spine.active = true;
            spine.getComponent(sp.Skeleton).setAnimation(0, "animation", false)

            spine.getComponent(sp.Skeleton).setCompleteListener(() => {
                spine.removeFromParent()
                spine.active = false;
                this.clearSpineNodePool.push(spine)
            })


        }).start()
    }

    showAndHidePath(start: [number, number], end: [number, number], type: string = 'show') {
        console.warn("执行路径动画" + type, start, end)
        let paths = GameLogicMgr.instance.findShortestPath(GameLogicMgr.instance.levelDataByNumberArr, start, end)
        for (let i = 0; i < paths.length; i++) {
            let path = paths[i]
            if (path[0] !== end[0] || path[1] !== end[1]) {
                const node = this.bgNodeBlocks[path[0]][path[1]].getChildByName("pathColor");
                Tween.stopAllByTarget(node.getComponent(UIOpacity))
                tween(node.getComponent(UIOpacity))
                    .by(0, { opacity: 0 })
                    .delay(i * 0.05)
                    .to(0.1, { opacity: 225 })
                    .call((target: UIOpacity) => {
                        tween(target)
                            .delay((i) * 0.1)
                            .to(0.2, { opacity: 0 })
                            .start()
                    })
                    .start()
            } else {
                const node = this.bgNodeBlocks[path[0]][path[1]].getChildByName("pathColor1");
                Tween.stopAllByTarget(node.getComponent(UIOpacity))
                tween(node.getComponent(UIOpacity))
                    .by(0, { opacity: 0 })
                    .delay(i * 0.05)
                    .to(0.1, { opacity: 225 })
                    .call((target: UIOpacity) => {
                        tween(target)
                            .delay((i) * 0.1)
                            .to(0.2, { opacity: 0 })
                            .start()
                    })
                    .start()
            }
        }
    }

    /**播放连击音效 */
    private playComboSound() {
        let spriteFrame = null;
        switch (GameDef.instance.comboCount) {
            case 0:
                break;
            case 1:
                spriteFrame = this.comboSprites[0]
                AudioMgr.getInstance().playEffect(AudioId.yes)
                break;
            case 2:
                spriteFrame = this.comboSprites[1]
                AudioMgr.getInstance().playEffect(AudioId.nice)
                break;
            case 3:
                spriteFrame = this.comboSprites[2]
                AudioMgr.getInstance().playEffect(AudioId.great)
                break;
            case 4:
                spriteFrame = this.comboSprites[3]
                AudioMgr.getInstance().playEffect(AudioId.perfect)
                break;
            case 5:
                spriteFrame = this.comboSprites[4]
                AudioMgr.getInstance().playEffect(AudioId.excellent)
                break;
            case 6:
                spriteFrame = this.comboSprites[5]
                AudioMgr.getInstance().playEffect(AudioId.unbelievable)
                break;
            default:
                spriteFrame = this.comboSprites[5]
                AudioMgr.getInstance().playEffect(AudioId.unbelievable)
                break;
        }
        if (!spriteFrame) return;
        const node = this.findChilds("lianjiAniNode");
        node.getComponent(Sprite).spriteFrame = spriteFrame
        Tween.stopAllByTarget(node)
        Tween.stopAllByTarget(node.getComponent(UIOpacity))
        node.getComponent(UIOpacity).opacity = 255
        node.setScale(v3(0, 0, 0))
        node.setPosition(v3(28, 0, 0))
        tween(node)
            .to(0.5, { scale: v3(1.2, 1.2, 1.2) }, { easing: easing.backOut })
            .delay(0.5)
            .to(0.5, { scale: v3(0, 0, 0), position: v3(28, 35, 0) })
            .start()
        tween(node.getComponent(UIOpacity))
            .delay(1)
            .to(0.5, { opacity: 0 })
            .call(() => {
                node.getComponent(UIOpacity).opacity = 255
                node.setScale(v3(0, 0, 0))
                node.setPosition(v3(28, 0, 0))
            }).start()


    }
    /**播放连击动画 */
    private playComboAni() {
        if (GameDef.instance.comboCount > 0) {
            // this.findChilds("comboNode").getComponent(Label).string = "连击 x" + (GameDef.instance.comboCount)
            // //    tween(this.findChilds("comboNode")).destroySelf()
            // this.findChilds("comboNode").setPosition(v3(0, 0, 0))
            // this.findChilds("comboNode").setScale(v3(0, 0, 0))
            // tween(this.findChilds("comboNode"))
            //     .to(0.2, { scale: v3(2, 2, 2), position: v3(0, 100, 0) })
            //     .to(1, { scale: v3(1, 1, 1), position: v3(0, 200, 0) })
            //     .to(0.1, { scale: v3(0, 0, 0) })
            //     .start()
        }
    }
    /**随机提示可以消除的节点  提示可以消除高亮*/
    private scaleColorBlockData: {
        //       y          x    maskCount maskType
        blocks: [number, number, number, number][];
        value: number;
        clickPos: number[];
    }
    /**技能-提示功能 */
    onClickHint(e, isFree = false) {
        console.log("点击了提示", e, isFree)
        if (this.useSkillStatu) { return; }
        let autoFindReult = GameLogicMgr.instance.findZeroBlocks()
        if (autoFindReult.length > 0) {
            if (isFree) {
                //免费---训练赛中直接显示
                let randomIndex = Math.floor(Math.random() * autoFindReult.length);
                let randomBlock = autoFindReult[randomIndex];
                //显示提示和动画效果信息
                this.scaleColorBlockData = randomBlock;
                this.showTipAniNode()
            } else {
                if (PlayerMgr.instance.getSkillCount(1) > 0) {
                    PlayerMgr.instance.setSkillCount(1, -1)
                    let randomIndex = Math.floor(Math.random() * autoFindReult.length);
                    let randomBlock = autoFindReult[randomIndex];
                    //显示提示和动画效果信息
                    this.scaleColorBlockData = randomBlock;
                    this.showTipAniNode()
                    this.refreshSkillBtnUI()
                    GameDef.instance.reportInfo.tip += 1;
                    return;
                }
                SDKMgr.getInstance().playVideo((isComp) => {
                    if (isComp) {
                        let randomIndex = Math.floor(Math.random() * autoFindReult.length);
                        let randomBlock = autoFindReult[randomIndex];
                        //显示提示和动画效果信息
                        this.scaleColorBlockData = randomBlock;
                        this.showTipAniNode()
                        GameDef.instance.reportInfo.tip += 1;
                        GameDef.instance.reportInfo.ad_video_times += 1;
                    }
                    SDKMgr.getInstance().reportEvent("showad", {
                        "adtype": "video",
                        "opportunity": ADType.SKILL1,
                        "passpercent": GameDef.instance.reportInfo.levelPorgress,
                        "video_complete": isComp + '',
                        "is_stage": "true",
                        "stage": `第${GameDef.instance.curLevel}关`,
                        "level_type": "主线"
                    })
                }, ADType.SKILL1)
            }
        }
    }
    /**显示动画和提示相关信息 */
    showTipAniNode() {
        console.log("this.scaleColorBlockData", this.scaleColorBlockData)
        let layerSize = this.findChilds("grid").getComponent(UITransform);
        let x = this.scaleColorBlockData.clickPos[1] * this.colorBlockSize + this.colorBlockSize / 2 - layerSize.width / 2
        let y = -(this.scaleColorBlockData.clickPos[0] * this.colorBlockSize + this.colorBlockSize / 2) + layerSize.height / 2 - 12
        this.findChilds("aniTip").active = true;
        this.findChilds("aniTip").scale = v3((this.colorBlockSize / 42) * 0.8, (this.colorBlockSize / 42) * 0.8, (this.colorBlockSize / 42) * 0.8)
        this.findChilds("aniTip").setPosition(
            v3(x, y, 0)
        )
        for (let k in this.scaleColorBlockData.blocks) {
            let item = this.scaleColorBlockData.blocks[k]
            AnimtorUtils.scale(this.nodeArr[item[0]][item[1]], 1.1, true)
        }
    }
    hiedTipAniNode() {
        if (!this.scaleColorBlockData) return;
        this.findChilds("aniTip").active = false;
        // for(let k in this.nodeArr){
        //     for(let j in this.nodeArr[k]){
        //         AnimtorUtils.stopScale(this.nodeArr[k][j]) 
        //     }
        // }
        for (let k in this.scaleColorBlockData.blocks) {
            let item = this.scaleColorBlockData.blocks[k]
            AnimtorUtils.stopScale(this.nodeArr[item[0]][item[1]])
        }
        this.scaleColorBlockData = null;
    }
    /**击碎一个色块 */
    onClickCrack(item: number[]) {
        if (this.useSkillStatu) { return; }
        if (PlayerMgr.instance.getSkillCount(2) > 0) {
            PlayerMgr.instance.setSkillCount(2, -1)
            GameLogicMgr.instance.skillUseStatus = true;
            this.refreshSkillBtnUI()
            GameDef.instance.reportInfo.knock += 1
            return;
        }
        SDKMgr.getInstance().playVideo((isComp) => {
            if (isComp) {
                GameLogicMgr.instance.skillUseStatus = true;
                GameDef.instance.reportInfo.ad_video_times += 1
                GameDef.instance.reportInfo.knock += 1
            }
            SDKMgr.getInstance().reportEvent("showad", {
                "adtype": "video",
                "opportunity": ADType.SKILL2,
                "passpercent": GameDef.instance.reportInfo.levelPorgress,
                "video_complete": isComp + '',
                "is_stage": "true",
                "stage": `第${GameDef.instance.curLevel}关`,
                "level_type": "主线"
            })
        }, ADType.SKILL2)
    }
    /**刷新代码 */
    onClickRefresh() {
        if (this.useSkillStatu) { return; }
        if (PlayerMgr.instance.getSkillCount(3) > 0) {
            PlayerMgr.instance.setSkillCount(3, -1)
            this.onClickRefreshVideo()
            this.refreshSkillBtnUI()
            GameDef.instance.reportInfo.refresh += 1
            return;
        }
        SDKMgr.getInstance().playVideo((isComp) => {
            if (isComp) {
                this.onClickRefreshVideo()
                GameDef.instance.reportInfo.refresh += 1
                GameDef.instance.reportInfo.ad_video_times += 1
            }
            SDKMgr.getInstance().reportEvent("showad", {
                "adtype": "video",
                "opportunity": ADType.SKILL3,
                "passpercent": GameDef.instance.reportInfo.levelPorgress,
                "video_complete": isComp + '',
                "is_stage": "true",
                "stage": `第${GameDef.instance.curLevel}关`,
                "level_type": "主线"
            })
        }, ADType.SKILL3)
    }
    /**刷新功能 */
    onClickRefreshVideo() {
        const _levelData = GameLogicMgr.instance.randomLevelDatas()
        const layerSize = this.findChilds("gameLayer").getComponent(UITransform);
        const size = this.colorBlockSize
        const itemObj: { [key: string]: ColorBlock[] } = {}
        for (let j = 0; j < this.nodeArr.length; j++) {
            for (let i = 0; i < this.nodeArr[j].length; i++) {
                if (this.nodeArr[j][i]) {
                    let itemJS = this.nodeArr[j][i].getComponent(ColorBlock)
                    itemJS.node.scale = v3(0, 0, 0)
                    itemJS.node.getChildByName("maskColor").active = false
                    itemJS.node.getChildByName("maskColorAll").active = false
                    if (itemObj[itemJS.type]) {
                        itemObj[itemJS.type].push(itemJS)
                    } else {
                        itemObj[itemJS.type] = [itemJS]
                    }
                    this.nodeArr[j][i].removeFromParent()
                    this.nodeArr[j][i] = null;
                }
            }
        }
        for (let j = 0; j < _levelData.length; j++) {
            for (let i = 0; i < _levelData[j].length; i++) {
                if (_levelData[j][i].value > 0) {
                    let item = itemObj[_levelData[j][i].value].pop()
                    if (!item) {
                        const node = instantiate(this.colorBlockPrefab)
                        item = node.getComponent(ColorBlock)
                        console.warn("警告：没有找到对应的色块，重新实例化一个")
                    }
                    item.x = i;
                    item.y = j;
                    item.type = _levelData[j][i].value
                    this.nodeArr[j][i] = item.node;
                    item.node?.skin(item.node.name, GameDef.instance.gameSkin)
                    this.setMaskColorSkin(item.node, _levelData[j][i].maskType)
                    item.node.setPosition((i * size + size / 2) - layerSize.width / 2, -(j * size + size / 2) + layerSize.height / 2);
                    tween(item.node).delay(0.04 * (j + i))
                        .to(0.15, { scale: v3(1.4, 1.4, 1.4) })
                        .to(0.15, { scale: v3(0.8, 0.8, 0.8) })
                        // .to(0.07, { scale: v3(0.95, 0.95, 0.95) })

                        .to(0.07, { scale: v3(1.08, 1.08, 1.08) })
                        .start()
                    this.findChilds("gameLayer").addChild(item.node)
                }
            }
        }
        AudioMgr.getInstance().playEffect(AudioId.refresh)
    }
    /**
     *  设置遮罩颜色
     * @param node 节点
     * @param maskType 遮罩类型 1-透明 2-不透明 
     */
    setMaskColorSkin(node: Node, maskType: number) {
        if (maskType === 1) {
            node.getChildByName("maskColor").active = true
            node.getChildByName("maskColor").skin("kuan1", GameDef.instance.gameSkin)
        } else if (maskType === 2) {
            node.getChildByName("maskColorAll").active = true
            node.getChildByName("maskColorAll").skin("kuan2", GameDef.instance.gameSkin)
        }
    }
    /**
     * 查找数据，如果某个色块总数量为1，则自动补齐一个相同的色块，添加到场景
     */
    completeColorBlock() {
        let _levelData = GameLogicMgr.instance.fillSingleColorBlocks();
        for (let j = 0; j < _levelData.length; j++) {
            for (let i = 0; i < _levelData[j].length; i++) {
                if (_levelData[j][i].value > 0) {
                    if (!this.nodeArr[j][i]) {
                        this.addColorNodeToLayer(i, j)
                        console.log("添加一个相同的色块", i, j);
                    }
                }
            }
        }
        console.log("补齐后的关卡数据", _levelData);
        console.log("已自动补齐")
    }
    protected update(dt: number): void {


        if (GameLogicMgr.instance.isPause) return;
        //连击逻辑计算
        this.clickTimer += dt;
        this.clearTimer += dt;
        GameDef.instance.currGameTime += dt;
        if (this.clearTimer <= GameDef.instance.clearTime) {
            this.findChilds("timeProBar").getComponent(Sprite).fillRange = Math.floor(((GameDef.instance.clearTime - this.clearTimer) / GameDef.instance.clearTime) * 100) / 100;
        } else {
            this.clearTimer = GameDef.instance.clearTime;
        }
    }
    //分数计算
    scoreCalculation() {
        /*************************************** START *********************************** */

        //积分加成卡倍数
        let cardMultip = this.isUseBoundCard ? 1.5 : 1;
        //基础得分                       消除得分基数                倍数           消除用时           30s
        let currScore = GameDef.instance.baseScore[this.gameType] * cardMultip * (1 - this.clearTimer / GameDef.instance.clearTime);
        //最低得分
        let lowestScore = GameDef.instance.baseLowestScore[this.gameType];
        //判断最终获取得分,如果小于最低得分，则设置为最低得分,否则设置为计算出的得分
        currScore = currScore < lowestScore * cardMultip ? lowestScore * cardMultip : currScore;//计算出得分档位
        let comboScore = currScore * (GameDef.instance.comboCount / GameDef.instance.comboMultiple);//计算连击分数
        let allScore = currScore + comboScore;
        //计算出当前档位分数
        GameDef.instance.currLevelTotalScore += allScore;

        /***********************************  END  ************************************* */

        /**档位积分 */
        let integralScore = this.getIntegralByScore(GameDef.instance.currLevelTotalScore, this.gameType);


        /**************************************** START ******************************** */

        /**倍数 */
        let cardMultip1 = this.isUseBoundCard ? 2 : 1;
        let integral = (GameDef.instance.comboCount + integralScore) * cardMultip1;
        //计算当前关卡积分
        GameDef.instance.currLevelTotalPoints += integral;

        /***********************************  END  ************************************* */

        // this.updataScoreText()
        this.animateScoreChange(
            GameDef.instance.currLevelTotalScore,
            GameDef.instance.currLevelTotalPoints
        );

        console.group("当前关卡总积分", GameDef.instance.currLevelTotalPoints);
        console.log("当前关卡总得分", GameDef.instance.currLevelTotalScore);
        console.log("积分加成卡倍数", cardMultip1);
        console.log("当前关卡积分加成卡倍数", cardMultip);
        console.log("currScore:", GameDef.instance.getCurrLevelScore(this.gameType, GameDef.instance.currLevelTotalScore));
        console.log("当前关卡连击次数", GameDef.instance.comboCount);
        console.groupEnd();

    }
    updataScoreText() {
        this.findChilds("scorePro").getComponent(Label).string = "x" + GameDef.instance.getCurrLevelPoints(this.gameType, GameDef.instance.currLevelTotalPoints) + "";
        let score = GameDef.instance.getCurrLevelScore(this.gameType, GameDef.instance.currLevelTotalScore);
        let range = GameDef.instance.currLevelTotalScore / score;
        range = range > 1 ? 1 : range;
        this.findChilds("scoreRange").getComponent(Label).string = Math.floor(GameDef.instance.currLevelTotalScore) + "/" + score;//积分:
        this.findChilds("score").getComponent(Label).string = "" + Math.floor(GameDef.instance.currLevelTotalPoints);//积分:
        this.findChilds("scoreProBar").getComponent(Sprite).fillRange = range;
        this.findChilds("scoreProFly").getComponent(Label).string = this.findChilds("scorePro").getComponent(Label).string
        this.findChilds("btn_jindu3").setPosition(v3(range * 625, 0, 0))
    }

    private animateScoreChange(targetScore: number, targetPoints: number) {
        const duration = 0.5; // 动画持续时间
        let pointScore = GameDef.instance.getCurrLevelPoints(this.gameType, GameDef.instance.currLevelTotalScore) + "";
        if ("x" + pointScore !== this.findChilds("scorePro").getComponent(Label).string) {
            this.pointScoreAni(this.findChilds("scorePro").getComponent(Label).string)
            this.currSkinInde++;
            if (this.currSkinInde >= 4) {
                this.currSkinInde = 4;
            }
            this.findChilds("chipang").getComponent(sp.Skeleton).setSkin('ka' + this.currSkinInde)

            //     this.findChilds("scoreProFly").active = true;
            //     tween(this.findChilds("scoreProFly"))
            //     .to(0.5,{position: v3(210, 97, 0),scale: v3(1.2, 1.2, 1.2)})
            //     .delay(0.5)
            //     .call(()=>{
            //         this.findChilds("scoreProFly").active = false;
            //         this.findChilds("scoreProFly").setPosition(v3(-298, -4, 0))
            //         this.findChilds("scoreProFly").setScale(v3(1, 1, 1)) 
            //     })
            //    .start()
        }
        console.log("pointScore", pointScore)
        this.findChilds("scorePro").getComponent(Label).string = "x" + pointScore
        this.findChilds("scoreProFly").getComponent(Label).string = this.findChilds("scorePro").getComponent(Label).string
        Tween.stopAllByTarget(this); // 停止之前的动画
        tween(this as any)
            .to(duration, {
                _tempScore: targetScore,
                _tempPoints: targetPoints
            }, {
                onUpdate: (target: this, ratio: number) => {
                    // 使用缓动函数实现先快后慢的效果
                    const easedRatio = easing.quadOut(ratio);
                    const currentScore = this.startScore + (targetScore - this.startScore) * easedRatio;
                    const currentPoints = this.startPoints + (targetPoints - this.startPoints) * easedRatio;
                    this.startScore = target._tempScore;
                    this.startPoints = target._tempPoints;
                    this.updateScoreDisplay(currentScore, currentPoints);
                }
            }).call(() => {
            })
            .start();

    }

    pointScoreAni(score: string) {
        const node = this.findChilds("jifenFlyIcon")
        node.active = false;
        node.setPosition(v3(-298, -4, 0))
        node.getChildByName("scoreProFly").getComponent(Label).string = score;
        node.active = true;
        tween(node)
            .to(0.5, { position: v3(197, 101, 0), scale: v3(1.2, 1.2, 1.2) }, { easing: easing.circOut })
            .call(() => {
                node.active = false;
                node.setPosition(v3(-298, -4, 0))
                node.setScale(v3(1, 1, 1))
            })
            .start()
    }

    // 修改原有方法为私有方法供动画调用
    private updateScoreDisplay(currentScore: number, currentPoints: number) {
        const score = GameDef.instance.getCurrLevelScore(this.gameType, currentScore);
        const range = currentScore / score;
        const finalRange = range > 1 ? 1 : range;

        // 更新所有分数相关UI
        // this.findChilds("scorePro").getComponent(Label).string =Math.floor(currentPoints) + "";
        this.findChilds("scoreRange").getComponent(Label).string = Math.floor(currentScore) + "/" + score;
        this.findChilds("score").getComponent(Label).string = Math.floor(currentPoints) + "";
        this.findChilds("scoreProBar").getComponent(Sprite).fillRange = finalRange;
        this.findChilds("btn_jindu3").setPosition(v3(finalRange * 625, 0, 0));
    }



    /**
    * 根据得分和游戏类型获取对应的积分档位
    * @param score 得分
    * @param type 游戏类型，数字类型，0: 训练营, 1: 初级, 2: 中级, 3: 高级
    * @returns 对应的积分档位，如果没有匹配的档位则返回 null
    */
    private getIntegralByScore(score: number, type: number): number {
        for (let i = GameDef.instance.scoreRanges.length - 1; i >= 0; i--) {
            const currentRange = GameDef.instance.scoreRanges[i];
            if (score >= currentRange.scores[type]) {
                if (!currentRange.isCurrLvGet) {
                    currentRange.isCurrLvGet = true;
                    console.log("+ " + currentRange.integral + "积分")
                    return currentRange.integral;
                }
            }
        }
        return 0;
    }
    onOpenRolue() {
        UIMgr.getInstance().openUI(UIID.UIRolue, UIID.Default)
    }
    get useSkillStatu() {
        if (this.scaleColorBlockData) {
            UIMgr.getInstance().showTip("请先消除当前色块");
            return true;
        }
        if (GameLogicMgr.instance.skillUseStatus) {
            UIMgr.getInstance().showTip("请敲碎一块色块");
            return true;
        }
        return false;
    }
    showGuide() {
        // if(!PlayerMgr.instance.isNewGuide) return
        let guideData = PlayerMgr.getInstance().getGuideData();
        if (!guideData.isGuideEnd()) {
            let guideCfg = new GuildCfg();
            guideCfg.closeUICallBack = () => {
                setTimeout(() => {
                    if (this.getGuideData(guideData.currentId)) {
                        this.showGuide()
                    }
                }, 500)
            }
            const data = this.getGuideData();
            guideCfg.distNode = data.distNode;
            guideCfg.isWeek = data.isWeek;
            guideCfg.tipstring = data.tipstring;
            guideCfg.handOffset = data.handOffset;
            this.openUICallBack(UIID.UIGuide, () => {
                guideData.addCurrentId(data.isEnd)
            }, guideCfg);

        }
    }

    getGuideData(id: number = null) {
        let guideData = PlayerMgr.getInstance().getGuideData();
        switch (id || guideData.currentId) {
            case 2:
                //引导
                return { distNode: this.findChilds("seep1"), tipstring: "跟着豚豚助手点击空白区域消除\n十字上相同的方块吧", isWeek: false, isEnd: false, handOffset: new Vec3(72, -90, 0) }
            case 3:
                //引导
                return { distNode: this.findChilds("seep2"), tipstring: "跟着豚豚助手点击空白区域消除\n十字上相同的方块吧", isWeek: false, isEnd: false, handOffset: new Vec3(-110, -150, 0) }
            case 4:
                //引导
                return { distNode: this.findChilds("bg_taimian"), tipstring: "每消除一次都会增长进度，进度条\n每满一次都能获得相应的奖励哦！", isWeek: true, isEnd: false, handOffset: new Vec3(0, -70, 0) }
            case 5:
                //引导
                return { distNode: this.findChilds("seep3"), tipstring: "十字上有两组不同的方块也可以\n同时消除哦", isWeek: false, isEnd: false, handOffset: new Vec3(70, -15, 0) }
        }

    }
    private skillTipTimer = 0;
    startShowSkillTip(t){
        this.skillTipTimer++;
        if(this.skillTipTimer==8){
            //随机显示一个技能
            let index = Math.floor(Math.random()*this.tipNodes.length)
            this.tipNodes[index].active = true;
        }
        
    }
    hideSkillTip(){
        this.skillTipTimer = 0;
        for(let i=0;i<this.tipNodes.length;i++){
            this.tipNodes[i].active = false;
        }
    }
    protected onDisable(): void {
        this.unschedule(this.onUpdata)
    }
    onUpdata() {
        this.tipTimes += 1;
        if (this.tipTimes == 5 * 60) {
            this.onClickHint(null, true)
        }
    }
}

